<template>
  <div class="attraction-management">
    <div class="page-header">
      <div class="title-section">
        <h1>景点管理</h1>
        <p class="subtitle">管理网站的所有景点信息，为用户提供优质的旅游内容</p>
      </div>
      <div class="action-section">
        <el-button type="primary" @click="goToCreateAttraction" :icon="Plus">
          添加景点
        </el-button>
      </div>
    </div>
    
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card">
      <div class="filter-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索景点名称"
          class="search-input"
          clearable
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select 
          v-model="categoryFilter" 
          placeholder="类别筛选" 
          clearable 
          @change="handleSearch"
          class="filter-select"
        >
          <el-option
            v-for="item in categories"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.categoryId"
          />
        </el-select>
        
        <el-select 
          v-model="statusFilter" 
          placeholder="状态筛选" 
          clearable 
          @change="handleSearch"
          class="filter-select"
        >
          <el-option label="上线" :value="1" />
          <el-option label="下线" :value="0" />
        </el-select>
        
        <el-select 
          v-model="ratingFilter" 
          placeholder="最低评分" 
          clearable 
          @change="handleSearch"
          class="filter-select"
        >
          <el-option label="4星以上" :value="4" />
          <el-option label="3星以上" :value="3" />
          <el-option label="2星以上" :value="2" />
        </el-select>
        
        <div class="filter-actions">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 景点列表 -->
    <el-card class="table-card" v-loading="loading">
      <div class="view-toggle">
        <el-radio-group v-model="viewMode" size="small">
          <el-radio-button label="table">表格视图</el-radio-button>
          <el-radio-button label="card">卡片视图</el-radio-button>
        </el-radio-group>
      </div>
      
      <!-- 表格视图 -->
      <el-table
        v-if="viewMode === 'table'"
        :data="attractions"
        style="width: 100%"
        border
      >
        <el-table-column type="index" width="50" />
        
        <el-table-column label="景点信息" min-width="300">
          <template #default="scope">
            <div class="attraction-info">
              <el-image 
                :src="getCoverImage(scope.row)" 
                fit="cover"
                class="attraction-image"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="attraction-details">
                <h3>{{ scope.row.name }}</h3>
                <p class="attraction-description">{{ scope.row.description }}</p>
                <div class="attraction-meta">
                  <el-tag size="small" type="info">{{ scope.row.categoryName }}</el-tag>
                  <span class="visit-count">
                    <el-icon><View /></el-icon> {{ formatNumber(scope.row.viewCount) }}
                  </span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="address" label="位置" min-width="150" show-overflow-tooltip />
        
        <el-table-column label="评分" width="120" align="center">
          <template #default="scope">
            <div class="rating-cell">
              <el-rate
                v-model="scope.row.avgRating"
                disabled
                text-color="#ff9900"
                :max="5"
              />
              <span class="rating-value">{{ scope.row.avgRating ? scope.row.avgRating.toFixed(1) : '0.0' }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="ticketPrice" label="门票价格" width="120" align="center" />
        
        <el-table-column label="标签" min-width="150" align="center">
          <template #default="scope">
            <div class="tags-container">
              <el-tag 
                v-for="(tag, index) in scope.row.tags" 
                :key="index"
                size="small"
                class="tag-item"
              >
                {{ tag }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '上线' : '下线' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="goToEditAttraction(scope.row.attractionId)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDeleteAttraction(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 卡片视图 -->
      <div v-else class="attractions-grid">
        <el-row :gutter="20">
          <el-col 
            v-for="attraction in attractions" 
            :key="attraction.attractionId"
            :xs="24" 
            :sm="12" 
            :md="8" 
            :lg="6"
          >
            <el-card class="attraction-card" :body-style="{ padding: '0px' }">
              <div class="card-cover">
                <el-image 
                  :src="getCoverImage(attraction)" 
                  fit="cover"
                  class="card-image"
                >
                  <template #error>
                    <div class="image-placeholder">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="card-status">
                  <el-tag :type="attraction.status === 1 ? 'success' : 'danger'" size="small">
                    {{ attraction.status === 1 ? '上线' : '下线' }}
                  </el-tag>
                </div>
                <div class="card-category">
                  <el-tag type="info" size="small">{{ attraction.categoryName }}</el-tag>
                </div>
              </div>
              <div class="card-content">
                <h3 class="card-title">{{ attraction.name }}</h3>
                <p class="card-description">{{ attraction.description }}</p>
                <div class="card-meta">
                  <div class="card-rating">
                    <el-rate
                      v-model="attraction.avgRating"
                      disabled
                      text-color="#ff9900"
                      :max="5"
                    />
                    <span>{{ attraction.avgRating ? attraction.avgRating.toFixed(1) : '0.0' }}</span>
                  </div>
                  <div class="card-visits">
                    <el-icon><View /></el-icon>
                    <span>{{ formatNumber(attraction.viewCount) }}</span>
                  </div>
                </div>
                <div class="card-tags">
                  <el-tag 
                    v-for="(tag, index) in attraction.tags" 
                    :key="index"
                    size="small"
                    class="tag-item"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
                <div class="card-actions">
                  <el-button
                    size="small"
                    type="primary"
                    @click="goToEditAttraction(attraction.attractionId)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleDeleteAttraction(attraction)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <!-- 空状态 -->
      <el-empty 
        v-if="attractions.length === 0 && !loading" 
        description="暂无景点数据" 
      >
        <el-button type="primary" @click="goToCreateAttraction">添加景点</el-button>
      </el-empty>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Picture, View } from '@element-plus/icons-vue';
import { getAttractionList, updateAttraction, deleteAttraction } from '@/api/attraction';
import { getAllCategories } from '@/api/category';

const router = useRouter();

// 视图模式
const viewMode = ref('table');

// 搜索和筛选
const searchQuery = ref('');
const categoryFilter = ref('');
const statusFilter = ref('');
const ratingFilter = ref('');

// 表格数据
const attractions = ref([]);
const categories = ref([]);
const loading = ref(false);

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取景点列表
const fetchAttractions = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      name: searchQuery.value || undefined,
      categoryId: categoryFilter.value || undefined,
      status: statusFilter.value !== '' ? statusFilter.value : undefined
    };
    
    const response = await getAttractionList(params);
    if (response.code === 200) {
      // 适配后端返回的数据结构
      attractions.value = response.data.list || response.data.records || [];
      total.value = response.data.total || 0;
      
      // 处理分类名称
      attractions.value.forEach(item => {
        if (item.category) {
          item.categoryName = item.category.categoryName;
        }
        // 确保viewCount字段存在（有些返回的是viewCount，有些是visitCount）
        if (item.visitCount !== undefined && item.viewCount === undefined) {
          item.viewCount = item.visitCount;
        }
      });
    } else {
      ElMessage.error(response.message || '获取景点列表失败');
    }
  } catch (error) {
    console.error('获取景点列表失败:', error);
    ElMessage.error('获取景点列表失败，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 获取类别列表
const fetchCategories = async () => {
  try {
    const response = await getAllCategories();
    
    if (response.code === 200 && response.data) {
      categories.value = response.data;
    } else {
      ElMessage.error(response.message || '获取类别列表失败');
    }
  } catch (error) {
    console.error('获取类别列表失败:', error);
    ElMessage.error('获取类别列表失败，请稍后再试');
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchAttractions();
};

// 重置筛选条件
const resetFilters = () => {
  searchQuery.value = '';
  categoryFilter.value = '';
  statusFilter.value = '';
  ratingFilter.value = '';
  currentPage.value = 1;
  fetchAttractions();
};

// 跳转到创建景点页面
const goToCreateAttraction = () => {
  router.push('/admin/attractions/create');
};

// 跳转到编辑景点页面
const goToEditAttraction = (id) => {
  router.push(`/admin/attractions/edit/${id}`);
};

// 切换景点状态
const handleToggleStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1;
  const statusText = newStatus === 1 ? '上线' : '下线';
  
  ElMessageBox.confirm(
    `确定要${statusText}景点 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const response = await updateAttraction(row.attractionId, {
          ...row,
          status: newStatus
        });
        
        if (response.code === 200) {
          ElMessage.success(`${statusText}景点成功`);
          fetchAttractions();
        } else {
          ElMessage.error(response.message || `${statusText}景点失败`);
        }
      } catch (error) {
        console.error(`${statusText}景点失败:`, error);
        ElMessage.error(`${statusText}景点失败，请稍后再试`);
      }
    })
    .catch(() => {
      // 用户取消操作
    });
};

// 删除景点
const handleDeleteAttraction = (row) => {
  ElMessageBox.confirm(
    `确定要删除景点 "${row.name}" 吗？此操作不可恢复！`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const response = await deleteAttraction(row.attractionId);
        
        if (response.code === 200) {
          ElMessage.success('删除景点成功');
          fetchAttractions();
        } else {
          ElMessage.error(response.message || '删除景点失败');
        }
      } catch (error) {
        console.error('删除景点失败:', error);
        ElMessage.error('删除景点失败，请稍后再试');
      }
    })
    .catch(() => {
      // 用户取消操作
    });
};

// 获取封面图片
const getCoverImage = (attraction) => {
  // 首先检查coverImages数组
  if (attraction.coverImages && attraction.coverImages.length > 0) {
    return attraction.coverImages[0];
  }
  // 然后检查coverImage字段（兼容旧数据）
  if (attraction.coverImage) {
    return attraction.coverImage;
  }
  // 如果都没有，返回默认图片
  return 'https://via.placeholder.com/300x200?text=No+Image';
};

// 格式化数字（访问量等）
const formatNumber = (num) => {
  if (num === undefined || num === null) return '0';
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchAttractions();
};

// 页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchAttractions();
};

onMounted(() => {
  fetchAttractions();
  fetchCategories();
});
</script>

<style scoped>
.attraction-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-section h1 {
  margin: 0 0 5px;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 150px;
}

.filter-actions {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

.table-card {
  margin-bottom: 20px;
}

.view-toggle {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 表格视图样式 */
.attraction-info {
  display: flex;
  align-items: flex-start;
  gap: 15px;
}

.attraction-image {
  width: 80px;
  height: 60px;
  border-radius: 4px;
  flex-shrink: 0;
}

.attraction-details {
  flex: 1;
  min-width: 0;
}

.attraction-details h3 {
  margin: 0 0 5px;
  font-size: 16px;
  font-weight: 600;
}

.attraction-description {
  margin: 0 0 5px;
  color: #606266;
  font-size: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.attraction-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.visit-count {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
  font-size: 12px;
}

.rating-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.rating-value {
  font-size: 14px;
  font-weight: bold;
  color: #ff9900;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  justify-content: center;
}

.tag-item {
  margin-right: 0;
}

/* 卡片视图样式 */
.attractions-grid {
  margin-bottom: 20px;
}

.attraction-card {
  height: 100%;
  transition: all 0.3s;
  margin-bottom: 20px;
}

.attraction-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.card-cover {
  position: relative;
  height: 180px;
}

.card-image {
  width: 100%;
  height: 100%;
}

.card-status {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 1;
}

.card-category {
  position: absolute;
  bottom: 10px;
  left: 10px;
  z-index: 1;
}

.card-content {
  padding: 15px;
}

.card-title {
  margin: 0 0 10px;
  font-size: 18px;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-description {
  margin: 0 0 15px;
  color: #606266;
  font-size: 14px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  height: 60px;
}

.card-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.card-rating {
  display: flex;
  align-items: center;
  gap: 5px;
}

.card-visits {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
  font-size: 14px;
}

.card-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-bottom: 15px;
  min-height: 32px;
}

.card-actions {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 10px;
}

.image-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 24px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .filter-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .filter-select {
    width: 100%;
  }
  
  .filter-actions {
    margin-left: 0;
    width: 100%;
    justify-content: space-between;
  }
}
</style> 